import React, { useState, useEffect } from "react";
import { 
  Button, 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  message, 
  Spin, 
  Card,
  Descriptions,
  Tag,
  Row,
  Col,
  Space
} from "antd";
import '../components.css';
import RepaymentScheduleService from "../../services/RepaymentScheduleService";
import { useParams, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import { 
  EditOutlined, 
  SaveOutlined, 
  CloseOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';

const { Option } = Select;

// 状态映射
const STATUS_MAPPING = {
  PENDING: { text: '未到期', color: 'blue' },
  PAID: { text: '已支付', color: 'green' },
  OVERDUE: { text: '已逾期', color: 'red' }
};

export default function RepaymentScheduleDetails() {
  const [formData, setFormData] = useState({});
  const [loading, setLoading] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const { id } = useParams();

  // 状态选项
  const statusOptions = [
    { value: 'PENDING', label: '未到期' },
    { value: 'PAID', label: '已支付' },
    { value: 'OVERDUE', label: '已逾期' }
  ];

  // 获取还款计划详情
  const fetchRepaymentScheduleDetails = () => {
    setLoading(true);
    RepaymentScheduleService.getRepaymentScheduleById(id)
      .then(response => {
        const data = response.data;
        setFormData(data);
        // 初始化表单值
        form.setFieldsValue({
          ...data,
          dueDate: data.dueDate ? dayjs(data.dueDate) : null
        });
      })
      .catch(error => {
        console.error('加载数据失败:', error);
        message.error('加载还款计划详情失败');
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    fetchRepaymentScheduleDetails();
  }, [id]);

  // 更新还款计划
  const updateRepaymentSchedule = () => {
    form.validateFields()
      .then(values => {
        setLoading(true);
        
        const repaymentSchedule = {
          ...values,
          dueDate: values.dueDate.format('YYYY-MM-DD'),
          period: parseInt(values.period),
          totalPeriods: parseInt(values.totalPeriods),
          principal: parseFloat(values.principal)
        };
        
        RepaymentScheduleService.updateRepaymentSchedule(id, repaymentSchedule)
          .then(response => {
            message.success('还款计划更新成功!');
            setIsEditing(false);
            fetchRepaymentScheduleDetails(); // 刷新数据
          })
          .catch(error => {
            console.error('更新失败:', error);
            message.error('更新还款计划失败: ' + (error.response?.data?.message || error.message));
          })
          .finally(() => {
            setLoading(false);
          });
      })
      .catch(errorInfo => {
        console.log('表单验证失败:', errorInfo);
      });
  };

  // 渲染详情视图
  const renderDetailView = () => (
    <Card 
      title="还款计划详情"
      bordered={false}
      style={{ borderRadius: '8px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
      extra={
        <Button 
          type="primary" 
          icon={<EditOutlined />}
          onClick={() => setIsEditing(true)}
        >
          编辑
        </Button>
      }
    >
      <Descriptions bordered column={1}>
        <Descriptions.Item label="合同编号">
          {formData.contractNumber}
        </Descriptions.Item>
        <Descriptions.Item label="客户名称">
          {formData.customerName}
        </Descriptions.Item>
        <Descriptions.Item label="期数">
          {formData.period} / {formData.totalPeriods}
        </Descriptions.Item>
        <Descriptions.Item label="本金">
          ¥{formData.principal?.toLocaleString()}
        </Descriptions.Item>
        <Descriptions.Item label="到期日">
          {formData.dueDate ? new Date(formData.dueDate).toLocaleDateString() : '-'}
        </Descriptions.Item>
        <Descriptions.Item label="状态">
          <Tag 
            color={STATUS_MAPPING[formData.status]?.color || 'default'}
            style={{ fontWeight: 'bold' }}
          >
            {STATUS_MAPPING[formData.status]?.text || formData.status}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="实际支付日期">
          {formData.paidDate ? new Date(formData.paidDate).toLocaleDateString() : '-'}
        </Descriptions.Item>
        <Descriptions.Item label="备注">
          {formData.remarks || '-'}
        </Descriptions.Item>
      </Descriptions>
    </Card>
  );

  // 渲染编辑表单
  const renderEditForm = () => (
    <Card 
      title="编辑还款计划"
      bordered={false}
      style={{ borderRadius: '8px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}
    >
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        autoComplete="off"
      >
        <Form.Item 
          label="合同编号" 
          name="contractNumber"
          rules={[{ required: true, message: '请输入合同编号!' }]}
        >
          <Input placeholder="请输入合同编号" readOnly={!isEditing} />
        </Form.Item>
        
        <Form.Item 
          label="客户名称" 
          name="customerName"
          rules={[{ required: true, message: '请输入客户名称!' }]}
        >
          <Input placeholder="请输入客户名称" readOnly={!isEditing} />
        </Form.Item>
        
        <Form.Item 
          label="当前期数" 
          name="period"
          rules={[{ required: true, message: '请输入当前期数!' }]}
        >
          <Input type="number" min={1} placeholder="请输入当前期数" readOnly={!isEditing} />
        </Form.Item>
        
        <Form.Item 
          label="总期数" 
          name="totalPeriods"
          rules={[{ required: true, message: '请输入总期数!' }]}
        >
          <Input type="number" min={1} placeholder="请输入总期数" readOnly={!isEditing} />
        </Form.Item>
        
        <Form.Item 
          label="本金" 
          name="principal"
          rules={[{ 
            required: true,
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入有效的本金金额 (如: 1000 或 1000.00)' 
          }]}
        >
          <Input prefix="¥" placeholder="请输入本金金额" readOnly={!isEditing} />
        </Form.Item>
        
        <Form.Item 
          label="到期日" 
          name="dueDate"
          rules={[{ required: true, message: '请选择到期日!' }]}
        >
          <DatePicker 
            format="YYYY-MM-DD" 
            style={{ width: '100%' }} 
            disabled={!isEditing}
            disabledDate={(current) => current && current < dayjs().startOf('day')}
          />
        </Form.Item>
        
        <Form.Item 
          label="状态" 
          name="status"
          rules={[{ required: true, message: '请选择还款状态!' }]}
        >
          <Select placeholder="请选择还款状态" disabled={!isEditing}>
            {statusOptions.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </Form.Item>
        
        <Form.Item 
          label="备注" 
          name="remarks"
        >
          <Input.TextArea placeholder="请输入备注" readOnly={!isEditing} rows={3} />
        </Form.Item>
        
        {isEditing && (
          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Space>
              <Button 
                type="primary" 
                icon={<SaveOutlined />}
                onClick={updateRepaymentSchedule}
              >
                保存
              </Button>
              <Button 
                icon={<CloseOutlined />}
                onClick={() => {
                  setIsEditing(false);
                  form.resetFields();
                  fetchRepaymentScheduleDetails();
                }}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        )}
      </Form>
    </Card>
  );

  return (
    <Spin spinning={loading}>
      <div className='repayment-details-container'>
        <Button 
          type="link" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/repaymentschedulelist')}
          style={{ marginBottom: 16 }}
        >
          返回列表
        </Button>
        
        <Row gutter={[24, 24]}>
          <Col span={24}>
            {isEditing ? renderEditForm() : renderDetailView()}
          </Col>
        </Row>
      </div>
    </Spin>
  );
}